package cn.edu.tsinghua.training.struts.demo.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import cn.edu.tsinghua.training.struts.demo.entity.User;
import cn.edu.tsinghua.training.struts.demo.util.DB;

public class UserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private User user;

	private static final String LOGIN = "select * from user where username=? and password=?";
	private static final String REGISTER = "insert into user values(null, ?, ?)";
	
	public String login() throws Exception {
		Connection connection = DB.getConnection();
		PreparedStatement preparedStatement = connection.prepareStatement(LOGIN);
		preparedStatement.setString(1, user.getUsername());
		preparedStatement.setString(2, user.getPassword());
		ResultSet resultSet = preparedStatement.executeQuery();
		boolean b = resultSet.next();
		DB.close(resultSet, preparedStatement, connection);
		if (b) {
			getSession().put("username", user.getUsername());
			return "login_success";
		} else {
			getRequest().put("message", "invalid username or password.");
			return "login_input";
		}
	}
	
	public String register() throws Exception {
		Connection connection = DB.getConnection();
		PreparedStatement preparedStatement = connection.prepareStatement(REGISTER);
		preparedStatement.setString(1, user.getUsername());
		preparedStatement.setString(2, user.getPassword());
		preparedStatement.executeUpdate();
		DB.close(null, preparedStatement, connection);
		return "register_success";
	}
	
	public String logout() throws Exception {
		getSession().clear();
		return "logout_success";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
}
